<?php

namespace App\Models\Kms\User;

use App\Models\Wanggui\CustomerDepartmentFollowUpRecordModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;


class KmsUser extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $table = "kf_fs_user";

    public $timestamps = false;


    const IS_EXITED_OK  = 1;  //已离职
    const IS_EXITED_OFF = 0;  //未离职


    /**
     * 离职状态
     */
    const IS_RESIGNED_ON  = 1;
    const IS_RESIGNED_OFF = 0;
    const IS_RESIGNED_MAPPING = [
        self::IS_RESIGNED_OFF => '在职',
        self::IS_RESIGNED_ON  => '离职',
    ];


    /**
     * Find the user instance for the given username.
     *
     * @param string $mobile
     * @return KmsUser
     */
    public function findForPassport(string $mobile): KmsUser
    {
        return $this->where('mobile', $mobile)->orderBy("id")->first();
    }

    /**
     * @param $password
     * @return bool
     */
    public function validateForPassportPasswordGrant($password): bool
    {
        return true;
    }

    /**
     * @return string
     */
    public function getAuthIdentifierName(): string
    {
        return "rmsUserId";
    }

    /**
     * @return HasOne
     */
    public function userConfigRel(): HasOne
    {
        return $this->hasOne(KmsUserConfigModel::class, "userId", "rmsUserId");
    }

    /**
     * @return Model|HasOne|object|null
     */
    public function lastLoginHistory()
    {
        return $this->hasOne(KmsUserLoginHistoryModel::class, "userId", "rmsUserId")->orderBy("id");
    }


    /**
     * 关联选址勘测任务
     * @return HasMany
     */
    public function siteTaskRel(): HasMany
    {
        return $this->hasMany(CustomerDepartmentTaskModel::class, 'assignId', 'rmsUserId');
    }


    /**
     * 关联最新跟进记录
     * @return HasMany
     */
    public function followUpLastRel(): HasMany
    {
        return $this->hasMany(CustomerDepartmentFollowUpRecordModel::class, 'createdByUid', 'rmsUserId')->orderByDesc('createdAt');
    }

    /**
     * 返回用户信息
     * @param array $rmsUserIds
     * @param string $rootDepartmentName
     * @return array
     */
    public static function getUserInfo(array $rmsUserIds = [], string $rootDepartmentName = '', ?int $isResigned = self::IS_RESIGNED_OFF): array
    {
        $userInfos = [];
        self::query()
            ->when(
                $rmsUserIds, function ($query) use ($rmsUserIds) {
                $query->whereIn('rmsUserId', $rmsUserIds);
            }
            )
            ->when(
                $rootDepartmentName, function ($query) use ($rootDepartmentName) {
                $query->where('rootDepartmentName', $rootDepartmentName);
            }
            )
            ->when($isResigned !== null, function ($query) use ($isResigned) {
                $query->where('isResigned', $isResigned);
            })
            ->get()
            ->each(
                function (KmsUser $kmsUser) use (&$userInfos) {
                    if ($kmsUser->rmsUserId != 0) {
                        $userInfos[$kmsUser->rmsUserId] = $kmsUser->name . '(' . $kmsUser->nickname . ')';
                    }
                }
            );

        return $userInfos;
    }

    /**
     * 获取标准的名称
     * @return string
     */
    public function getStandardNameAttribute(): string
    {
        return $this->name . '(' . $this->nickname . ')';
    }
}
